using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerCon : MonoBehaviour
{
    private readonly float maxBounceAngle = 75f;
    private float _paddleHalfWidth; // 挡板宽度的一半
    private float _leftBound;       // 左边界
    private float _rightBound;      // 右边界

    private readonly float moveSpeed = 30f;
    private int bricks;
    private bool isNextLevel = false;
    void Start()
    {
        // 获取挡板宽度
        _paddleHalfWidth = GetComponent<Collider2D>().bounds.size.x * 0.5f;

        // 获取屏幕左右边界的世界坐标
        Camera mainCamera = Camera.main;
        Vector2 leftEdge = mainCamera.ViewportToWorldPoint(new Vector2(0, 0)); // 左边界
        Vector2 rightEdge = mainCamera.ViewportToWorldPoint(new Vector2(1, 0)); // 右边界

        // 计算实际可移动范围
        _leftBound = leftEdge.x + _paddleHalfWidth;
        _rightBound = rightEdge.x - _paddleHalfWidth;
    }

    void Update()
    {
        int level = FindObjectOfType<GameManager>().level;
        // 横向输入
        float horizontal = Input.GetAxis("Horizontal");
        Vector3 moveDelta = new Vector3(horizontal * moveSpeed * Time.deltaTime, 0, 0);

        // 移动挡板
        transform.Translate(moveDelta);

        // 限制位置在屏幕内
        float clampedX = Mathf.Clamp(transform.position.x, _leftBound + 0.8f, _rightBound  - 0.8f);
        transform.position = new Vector3(clampedX, transform.position.y, transform.position.z);

        bricks = GameObject.FindGameObjectsWithTag("Brick").Length;
        if (bricks <= 0 && !isNextLevel)
        {
            
            FindObjectOfType<GameManager>().LoadLevel(level+1);
            isNextLevel = true;
        }

        if (Input.GetKeyDown(KeyCode.Escape))
        {
            FindObjectOfType<GameManager>().LoadLevel(level);
        }
    }

    public void ResetPosion()
    {
        this.transform.position = new Vector2(0, -8f) ;
    }

    private void OnCollisionEnter2D(Collision2D collision)

    {
        if (collision.gameObject.CompareTag("Ball"))
        {
            #region 重新定位发射方向
            BallCon ball1 = collision.gameObject.GetComponent<BallCon>();

            if (ball1 == null) return;

            Rigidbody2D ball = collision.rigidbody;

            Collider2D paddle = collision.otherCollider; // Gather information about the collision

            Vector2 ballDirection = ball.velocity.normalized;

            Vector2 contactDistance = paddle.bounds.center - ball.transform.position; // Rotate the direction of the ball based on the contact distance

            // to make the gameplay more dynamic and interesting

            float bounceAngle = (contactDistance.x / paddle.bounds.size.x) * maxBounceAngle;

            ballDirection = Quaternion.AngleAxis(bounceAngle, Vector3.forward) * ballDirection; // Re-apply the new direction to the ball

            ball.velocity = ballDirection.normalized * ball.velocity.magnitude;
            #endregion
        }
    }
}
